from django.shortcuts import render
from .serializers import *
from utils.permission import *
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination  # 分页
from rest_framework.viewsets import ModelViewSet,GenericViewSet
from rest_framework.decorators import action  # 行为路由装饰器
from django.db.models import F  # 查询模块
from rest_framework.mixins import CreateModelMixin,DestroyModelMixin  # 创建和删除
from rest_framework.viewsets import ModelViewSet,GenericViewSet

# Create your views here.
class TopicPageNumberPagination(PageNumberPagination):
    page_size = 20  # 每一页有多少条
    page_size_query_param = 'size'  # 控制每页可以有多少数据
    max_page_size = 100  # 最大每页多少条



# 文章视图集
class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False)  # 查询集
    serializer_class = ArticleSerializer  # 需要使用的序列化器
    # 要求用户先登录，才能够访问该视图类
    permission_classes = [IsAuthenticated]
    pagination_class = TopicPageNumberPagination

    def get_queryset(self):
        if self.action in ['list','retrieve']:
            return Article.objects.filter(is_delete=False,status=1)
        return self.queryset

    # 创建
    @auto_user
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    # 修改 要求是该作者才能够修改该作者的文章
    @update_auto_user
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    # 删除
    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    # 查询作者自己发布过的所有文章，包括未发布的文章
    @action(methods=['get'], detail=False)  # 访问
    def my(self, request):
        data = self.get_queryset().filter(user=request.user)
        serializer = self.get_serializer(data,many=True)
        return Response(serializer.data)
    # 浏览量
    def retrieve(self, request, *args, **kwargs):
        self.get_queryset().filter(id=kwargs['pk']).update(page_view=F('page_view')+1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    # 查看文章评论
    @action(methods=['get'], detail=True)  # 访问
    def comment(self, request,pk):
        comments = Comment.objects.filter(article_id=pk,level=1)
        serializer = CommentSerializer(comments,many=True)
        return Response(serializer.data)



# 评论视图集
class CommentViewSet(GenericViewSet,CreateModelMixin,DestroyModelMixin):
    queryset = Comment.objects.filter(is_delete=False,article__status=1)  # 查询集
    serializer_class = CommentSerializer  # 需要使用的序列化器
    # 要求用户先登录，才能够访问该视图类
    permission_classes = [IsAuthenticated]
    # 创建
    # @auto_user
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    # 删除
    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)


